package sunhapper.me.dagger2.mvvm.repository;

import javax.inject.Inject;

import io.reactivex.Flowable;
import io.reactivex.functions.Consumer;
import sunhapper.me.dagger2.api.WanAndroidApiService;
import sunhapper.me.dagger2.bean.User;
import sunhapper.me.dagger2.commons.RxUtil;
import sunhapper.me.dagger2.commons.SharedPreferenceHelper;
import sunhapper.me.dagger2.mvvm.datasource.WanAndroidDataSource;

/**
 * Created by sunhapper(haipeng.sun3@56qq.com) on 2018/9/12 .
 */
public class WanAndroidRepository {
    @Inject
    WanAndroidDataSource mWanAndroidDataSource;
    @Inject
    WanAndroidApiService mWanAndroidApiService;
    @Inject
    SharedPreferenceHelper mPreferenceHelper;

    @Inject
    public WanAndroidRepository() {
    }

    public Flowable<User> login(String userName, String pwd) {
        return mWanAndroidApiService
                .login(userName, pwd)
                .flatMap(RxUtil.<User>getRxNetworkErrorFun())
                .doOnNext(new Consumer<User>() {
                    @Override
                    public void accept(User user) throws Exception {
                        mWanAndroidDataSource.insertOrReplaceUser(user);
                        mPreferenceHelper.putLoginUserId(user.id);
                    }
                });
    }

    public User getLoginUserInfo() {
        if (isLogin()) {
            return mWanAndroidDataSource.getUser(mPreferenceHelper.getLoginUserId());
        } else {
            return null;
        }
    }

    public User getLocalUserInfo(int userId) {
        return mWanAndroidDataSource.getUser(userId);
    }

    public boolean isLogin() {
        return mPreferenceHelper.getLoginUserId() != SharedPreferenceHelper.UNLOGIN_USER_ID;
    }

}
